<?php
namespace app\manage\controller;
use app\common\lib\util\RpcClient;
use think\Db;

class GameList extends Base
{
    //游戏列表
    public function index()
    {
        return view();
    }

    //游戏主体
    public function app()
    {
        if (request()->isAjax()) {
            $page = input('page');
            $limit = input('limit');
            $appId = input('app_id');
            $appClassId = input('app_class_id');
            $tags = input('tags');

            $where['status'] = ['<>', -1];
            !empty($appId) && $where['app_id'] = $appId;
            !empty($appClassId) && $where['app_class_id'] = $appClassId;
            !empty($tags) && $where[] = ['exp', "FIND_IN_SET({$tags}, tags)"];

            if (!$count = Db::name('App')->where($where)->count()) {
                $this->layTable();
            }

            $select = Db::name('App')
                ->where($where)
                ->limit(($page - 1) * $limit, $limit)
                ->order('add_time desc')
                ->select();

            $data = [];

            $classIdName = changeValKey('AppClass', 'id', 'name');
            $tagIdName = changeValKey('AppTag', 'id', 'name');

            foreach ($select as $k => $v) {
                $tagsArr = explode(',', $v['tags']);
                $tagsStr = '';
                foreach ($tagsArr as $a => $b) {
                    if (isset($tagIdName[$b])) {
                        $tagsStr .= $tagIdName[$b] . ',';
                    }
                }
                $tagsStr = rtrim($tagsStr, ',');

                $data[] = [
                    'app_id' => $v['app_id'],
                    'app_name' => $v['app_name'],
                    'add_time' => $v['add_time'] ? date('Y-m-d H:i:s', $v['add_time']) : '',
                    'app_class_id' => isset($classIdName[$v['app_class_id']]) ? $classIdName[$v['app_class_id']] : '',
                    'tags' => $tagsStr,
                    'status' => $v['status'],
                    'language' => $v['language']
                ];
            }
            $this->layTable(0, '游戏主体', $data, $count);
        } else {
            $appId = Db::name('App')->where('status', '<>', -1)->order('app_id desc')->select();
            $appClassId = Db::name('AppClass')->select();
            $appTagId = Db::name('AppTag')->select();
            return view('', ['app_id' => $appId, 'app_class_id' => $appClassId, 'app_tag_id' => $appTagId]);
        }
    }

    //游戏主体添加
    public function appAdd()
    {
        if (request()->isAjax()) {
            $appName = input('app_name');
            $tagsStr = input('tags');
            $appClassId = input('app_class_id');
            $language = input('language');
            $introduction = input('introduction');
            $content = input('content');

            //验证游戏名称
//            if (Db::name('App')->where('app_name', $appName)->count()) {
//                $this->layJson(1, '游戏名称已存在');
//            }

//            $appId = Db::name('App')->max('app_id') + 1;

            $tagsArr = Db::name('AppTag')->where(['name' => ['in', $tagsStr]])->column('id');
            $tags = join(',', $tagsArr);

//            $add = Db::name('App')->insert([
//                'app_id' => $appId,
//                'app_name' => $appName,
//                'add_time' => time(),
//                'status' => 1,
//                'app_class_id' => $appClassId,
//                'tags' => $tags,
//                'introduction' => $introduction,
//                'language' => $language,
//                'content' => $content,
//            ]);

            $data=[
                'app_name' => $appName,
                'add_time' => time(),
                'status' => 1,
                'app_class_id' => $appClassId,
                'tags' => $tags,
                'introduction' => $introduction,
                'language' => $language,
                'content' => $content,
            ];
            $rs = RpcClient::call('App','add',[$data]);
            $rs ? $this->layJson(0, '添加成功') : $this->layJson(1, '添加失败，请重试');
        } else {
            $appClassId = Db::name('AppClass')->select();
            $appTagId = Db::name('AppTag')->select();

            return view('', ['app_class_id' => $appClassId, 'app_tag_id' => $appTagId]);
        }
    }

    //游戏主体编辑
    public function appEdit()
    {
        if (request()->isAjax()) {
            $appId = input('app_id');
            $appName = input('app_name');
            $tags = input('tags');
            $appClassId = input('app_class_id');
            $language = input('language');
            $introduction = input('introduction');
            $content = input('content');
            $status = input('status');

            if (isset($status)) {
                //$status = Db::name('App')->where('app_id', $appId)->update(['status' => $status]);
                $rs = RpcClient::call('App','update',[$appId,['status' => $status]]);
                $rs ? $this->layJson(0, '修改成功') : $this->layJson(1, '修改失败:'.RpcClient::getError());
            }

            //验证游戏名称
            $where['app_name'] = $appName;
            $where['app_id'] = ['<>', $appId];
            if (Db::name('App')->where($where)->count()) {
                $this->layJson(1, '游戏名称已存在');
            }

            $data = [
                'app_name' => $appName,
                'app_class_id' => $appClassId,
                'tags' => $tags,
                'introduction' => $introduction,
                'language' => $language,
                'content' => $content,
            ];
            //$update = Db::name('App')->where('app_id', $appId)->update($data);
            $rs = RpcClient::call('App','update',[$appId,$data]);

            $rs ? $this->layJson(0, '编辑成功') : $this->layJson(1, '编辑失败:'.RpcClient::getError());
        } else {
            $appClassId = Db::name('AppClass')->select();
            $appTagId = Db::name('AppTag')->select();

            $find = Db::name('App')->where('app_id', input('app_id'))->find();

            $tags = explode(',', $find['tags']);
            $tagIdName = changeValKey('AppTag', 'id', 'name');
            $myTag = '';
            foreach ($tags as $v) {
                if (isset($tagIdName[$v])) {
                    $myTag .= $tagIdName[$v] . ',';
                }
            }
            $myTag = rtrim($myTag, ',');

            return view('', ['app_class_id' => $appClassId, 'app_tag_id' => $appTagId, 'find' => $find, 'my_tag' => $myTag]);
        }
    }

    //游戏主体删除
    public function appDel()
    {
        $delRs = Db::name('App')->where('app_id', input('app_id'))->update(['status' => -1]);
        $delRs !== false ? $this->layJson(0, '删除成功') : $this->layJson(1, '删除失败，请重试');
    }

    //游戏主体资质文件
    public function document()
    {
        $appId = input('app_id');
        $documentPath = ROOT_PATH . 'uploads/document';
        $appPath = $documentPath.'/'.$appId;
        !is_dir($documentPath) && mkdir($documentPath);
        !is_dir($appPath) && mkdir($appPath);

        $arr = [];
        $newArr = [];
        $handle = opendir($appPath);
        while (false !== ($file = readdir($handle))){
            if($file=='.' || $file=='..') continue;
            $path = pathinfo(iconv("GB2312//IGNORE", "UTF-8", $file));
            $fileName = $path['filename'];

            if($fileName==$appId.'_'.'软著'){
                $newArr[1] = iconv("GB2312//IGNORE", "UTF-8", $file);
            }else if($fileName==$appId.'_'.'授权书'){
                $newArr[2] = iconv("GB2312//IGNORE", "UTF-8", $file);
            }else if($fileName==$appId.'_'.'版号'){
                $newArr[3] = iconv("GB2312//IGNORE", "UTF-8", $file);
            }else if($fileName==$appId.'_'.'批复'){
                $newArr[4] = iconv("GB2312//IGNORE", "UTF-8", $file);
            }
        }

        if(isset($newArr[1])){
            $arr[] = [
                'id' => 'upload1',
                'name' => '软著',
                'file_name' => $newArr[1]
            ];
        }else{
            $arr[] = [
                'id' => 'upload1',
                'name' => '软著',
                'file_name' => ''
            ];
        }
        if(isset($newArr[2])){
            $arr[] = [
                'id' => 'upload2',
                'name' => '授权书',
                'file_name' => $newArr[2]
            ];
        }else{
            $arr[] = [
                'id' => 'upload2',
                'name' => '授权书',
                'file_name' => ''
            ];
        }
        if(isset($newArr[3])){
            $arr[] = [
                'id' => 'upload3',
                'name' => '版号',
                'file_name' => $newArr[3]
            ];
        }else{
            $arr[] = [
                'id' => 'upload3',
                'name' => '版号',
                'file_name' => ''
            ];
        }
        if(isset($newArr[4])){
            $arr[] = [
                'id' => 'upload4',
                'name' => '批复',
                'file_name' => $newArr[4]
            ];
        }else{
            $arr[] = [
                'id' => 'upload4',
                'name' => '批复',
                'file_name' => ''
            ];
        }

        if(!$arr){
            $arr = [
                [
                    'id' => 'upload1',
                    'name' => '软著',
                    'file_name' => ''
                ],
                [
                    'id' => 'upload2',
                    'name' => '授权书',
                    'file_name' => ''
                ],
                [
                    'id' => 'upload3',
                    'name' => '版号',
                    'file_name' => ''
                ],
                [
                    'id' => 'upload4',
                    'name' => '批复',
                    'file_name' => ''
                ],
            ];
        }
        return view('', ['arr'=>$arr]);
    }

    //游戏主体资质文件上传
    public function upload1(){
        $file = request()->file('file');
        $appId = input('app_id');
        $name = iconv("UTF-8", "GB2312//IGNORE", input('name'));
        $originPath = ROOT_PATH . 'uploads/document/'.$appId;

        //上传文件，验证后缀跟文件大小，同名覆盖
        $info = $file
            ->validate(['size' => 2000000, 'ext' => 'png,jpg,pdf'])//2M
            ->move($originPath, $appId.'_'.$name);
        if (!$info) {
            $this->layJson(1, $file->getError());
        }
        $this->layJson(0, '上传成功', iconv("GB2312//IGNORE", "UTF-8", $info->getSaveName()));
    }

    public function del1(){
        $originPath = ROOT_PATH . 'uploads/document/'.input('app_id').'/'.input('file_name');
        @unlink(iconv("UTF-8", "GB2312//IGNORE", $originPath));
        $this->layJson(0, '删除成功');
    }

    public function get1(){
        $originPath = iconv("UTF-8", "GB2312//IGNORE", ROOT_PATH . 'uploads/document/'.input('app_id').'/'.input('file_name'));
        $info = getimagesize($originPath);
        header("content-type:".$info['mime']);
        header("content-disposition:attachment;filename=".input('file_name'));
        header("content-length:".filesize($originPath));
        echo file_get_contents($originPath);
    }//

    //游戏版本
    public function server()
    {
        if (request()->isAjax()) {
            $page = input('page');
            $limit = input('limit');
            $appId = input('app_id');
            $appTypeId = input('app_type_id');
            $appPublishTypeId = input('app_publish_type_id');

            $where['status'] = ['<>', -1];
            !empty($appId) && $where['app_id'] = $appId;
            !empty($appTypeId) && $where['app_type_id'] = $appTypeId;
            !empty($appPublishTypeId) && $where['app_publish_type_id'] = $appPublishTypeId;

            if (!$count = Db::name('AppServer')->where($where)->count()) {
                $this->layTable();
            }

            $select = Db::name('AppServer')
                ->where($where)
                ->limit(($page - 1) * $limit, $limit)
                ->order('id desc')
                ->select();

            $data = [];
            $appIdName = changeValKey('App', 'app_id', 'app_name');
            $appTypeIdName = changeValKey('AppType', 'id', 'name');
            $appPublishIdName = changeValKey('AppPublishType', 'id', 'name');
            foreach ($select as $k => $v) {
                $data[] = [
                    'id' => $v['id'],
                    'server_name' => $v['server_name'],
                    'app_id' => $v['app_id'],
                    'app_name' => isset($appIdName[$v['app_id']]) ? $appIdName[$v['app_id']] : '',
                    'app_type_id' => isset($appTypeIdName[$v['app_type_id']]) ? $appTypeIdName[$v['app_type_id']] : '',
                    'app_publish_type_id' => isset($appPublishIdName[$v['app_publish_type_id']]) ? $appPublishIdName[$v['app_publish_type_id']] : '',
                    'game_name' => $v['game_name'],
                    'code' => $v['code'],
                    'secret' => $v['secret'],
                    'add_time' => date('Y-m-d H:i:s', $v['add_time']),
                    'status' => $v['status'],
                    'charge_rate' => $v['charge_rate'],
                    'icon' => $v['icon'],
                ];
            }
            $this->layTable(0, '游戏版本', $data, $count);
        } else {
            $appId = Db::name('App')->where('status', '<>', -1)->order('app_id desc')->select();
            $appTypeId = Db::name('AppType')->select();
            $appPublishTypeId = Db::name('AppPublishType')->select();
            return view('', ['app_id' => $appId, 'app_type_id' => $appTypeId, 'app_publish_type_id' => $appPublishTypeId]);
        }
    }

    //游戏版本添加
    public function serverAdd()
    {
        if (request()->isAjax()) {
            $appId = input('app_id');
            $appTypeId = input('app_type_id');
            $appPublishTypeId = input('app_publish_type_id');
            $serverName = input('server_name');
            $gameName = input('game_name');
            $chargeRate = input('charge_rate');
            $icon = input('icon');

            //验证游戏名称
            $where['app_id'] = $appId;
            $where['app_type_id'] = $appTypeId;
            $where['app_publish_type_id'] = $appPublishTypeId;
            if (Db::name('AppServer')->where($where)->count()) {
                $this->layJson(1, '已经存在该版本，请重新选择');
            }

            $code = transPinyin($gameName) . rand(1000, 9999);
            $secret = md5(time() . 'ga!@^%890DFSFS!Q3589Hd' . $code);

            $add = Db::name('AppServer')->insert([
                'server_name' => $serverName,
                'app_id' => $appId,
                'app_type_id' => $appTypeId,
                'app_publish_type_id' => $appPublishTypeId,
                'game_name' => $gameName,
                'code' => $code,
                'secret' => $secret,
                'add_time' => time(),
                'status' => 1,
                'charge_rate' => $chargeRate,
                'icon' => $icon,
            ]);

            $add ? $this->layJson(0, '添加成功') : $this->layJson(1, '添加失败，请重试');
        } else {
            $appId = Db::name('App')->where('status', '<>', -1)->order('app_id desc')->select();
            $appTypeId = Db::name('AppType')->select();
            $AppPublishTypeId = Db::name('AppPublishType')->select();

            return view('', ['app_id' => $appId, 'app_type_id' => $appTypeId, 'app_publish_type_id' => $AppPublishTypeId]);
        }
    }

    //游戏版本编辑
    public function serverEdit()
    {
        if (request()->isAjax()) {
            $id = input('id');
            $appId = input('app_id');
            $appTypeId = input('app_type_id');
            $appPublishTypeId = input('app_publish_type_id');
            $serverName = input('server_name');
            $gameName = input('game_name');
            $chargeRate = input('charge_rate');
            $icon = input('icon');
            $status = input('status');

            if (isset($status)) {
                $update = Db::name('AppServer')->where('id', $id)->update(['status' => $status]);
                $update !== false ? $this->layJson(0, '修改成功') : $this->layJson(1, '修改失败，请重试');
            }

            //验证游戏名称
            $where['app_id'] = $appId;
            $where['app_type_id'] = $appTypeId;
            $where['app_publish_type_id'] = $appPublishTypeId;
            $where['id'] = ['<>', $id];
            if (Db::name('AppServer')->where($where)->count()) {
                $this->layJson(1, '已经存在该版本，请重新选择');
            }

            $data = [
                'server_name' => $serverName,
                'app_id' => $appId,
                'app_type_id' => $appTypeId,
                'app_publish_type_id' => $appPublishTypeId,
                'game_name' => $gameName,
                'charge_rate' => $chargeRate,
                'icon' => $icon,
            ];

            //如果改了名字，则修改code
            $oldName = Db::name('AppServer')->where('id', $id)->value('game_name');
            if ($oldName != $gameName) {
                $data['code'] = transPinyin($gameName) . rand(1000, 9999);
            }

            $update = Db::name('AppServer')->where('id', $id)->update($data);

            $update !== false ? $this->layJson(0, '编辑成功') : $this->layJson(1, '编辑失败，请重试');
        } else {
            $find = Db::name('AppServer')->where('id', input('id'))->find();
            $appId = Db::name('App')->where('status', '<>', -1)->order('app_id desc')->select();
            $appTypeId = Db::name('AppType')->select();
            $AppPublishTypeId = Db::name('AppPublishType')->select();

            return view('', ['find' => $find, 'app_id' => $appId, 'app_type_id' => $appTypeId, 'app_publish_type_id' => $AppPublishTypeId]);
        }
    }

    //游戏版本删除
    public function serverDel()
    {
        $delRs = Db::name('AppServer')->where('id', input('id'))->update(['status' => -1]);
        $delRs !== false ? $this->layJson(0, '删除成功') : $this->layJson(1, '删除失败，请重试');
    }

    //游戏终端
    public function client()
    {
        if (request()->isAjax()) {
            $page = input('page');
            $limit = input('limit');
            $gameId = input('game_id');
            $appPlatformTypeId = input('app_platform_type_id');
            $appClientTypeId = input('app_client_type_id');

            $where['status'] = ['<>', -1];
            !empty($gameId) && $where['game_id'] = $gameId;
            !empty($appPlatformTypeId) && $where['app_platform_type_id'] = $appPlatformTypeId;
            !empty($appClientTypeId) && $where['app_client_type_id'] = $appClientTypeId;

            if (!$count = Db::name('Game')->where($where)->count()) {
                $this->layTable();
            }

            $select = Db::name('Game')
                ->where($where)
                ->limit(($page - 1) * $limit, $limit)
                ->order('add_time desc')
                ->select();

            $data = [];
            $appPlatformIdName = changeValKey('appPlatformType', 'id', 'name');
            $appClientIdName = changeValKey('appClientType', 'id', 'name');
            $appServerIdSecret = changeValKey('appServer', 'id', 'secret');
            foreach ($select as $k => $v) {
                $data[] = [
                    'game_id' => $v['game_id'],
                    'game_name' => $v['game_name'],
                    'app_platform_type_id' => isset($appPlatformIdName[$v['app_platform_type_id']]) ? $appPlatformIdName[$v['app_platform_type_id']] : '',
                    'app_client_type_id' => isset($appClientIdName[$v['app_client_type_id']]) ? $appClientIdName[$v['app_client_type_id']] : '',
                    'package_size' => round($v['package_size'] / 1024 / 1024, 2) . 'MB',
                    'package_name' => $v['package_name'],
                    'up_location' => $v['up_location'] ? '金山云' : 'CDN',
                    'sdk_version' => $v['sdk_version'],
                    'h5_game_url' => $v['h5_game_url'],
                    'online_time_region' => explodeGameTime($v['online_time_region']),
                    'plat_show_region' => explodeGameTime($v['plat_show_region']),
                    'charge_time_region' => explodeGameTime($v['charge_time_region']),
                    'reg_time_region' => explodeGameTime($v['reg_time_region']),
                    'login_time_region' => explodeGameTime($v['login_time_region']),
                    'pack_time_region' => explodeGameTime($v['pack_time_region']),
                    'last_update_time' => date('Y-m-d H:i:s', $v['last_update_time']),
                    'add_time' => date('Y-m-d H:i:s', $v['add_time']),
                    'status' => $v['status'],
                    'pay_callback' => $v['pay_callback'],
                    'rebate_callback' => $v['rebate_callback'],
                    'gm_callback' => $v['gm_callback'],
                    'secret' => $v['secret']
                ];
            }
            $this->layTable(0, '游戏终端', $data, $count);
        } else {
            $gameId = Db::name('Game')->where('status', '<>', -1)->order('game_id desc')->select();
            $appPlatformTypeId = Db::name('AppPlatformType')->select();
            $appClientTypeId = Db::name('AppClientType')->select();
            return view('', ['game_id' => $gameId, 'app_platform_type_id' => $appPlatformTypeId, 'app_client_type_id' => $appClientTypeId]);
        }
    }

    //游戏终端添加
    public function clientAdd()
    {
        if (request()->isAjax()) {
            $gameName = input('game_name');
            $appServerId = input('app_server_id');
            $appPlatformTypeId = input('app_platform_type_id');
            $appClientTypeId = input('app_client_type_id');
            $upLocation = input('up_location');
            $sdkVersion = input('sdk_version');
            $h5GameUrl = input('h5_game_url');
            $payCallback = input('pay_callback');
            $rebateCallback = input('rebate_callback');
            $gmCallback = input('gm_callback');
            $secret = input('secret');
            $onlineTimeRegion = input('online_time_region');
            $platShowRegion = input('plat_show_region');
            $chargeTimeRegion = input('charge_time_region');
            $regTimeRegion = input('reg_time_region');
            $loginTimeRegion = input('login_time_region');
            $packTimeRegion = input('pack_time_region');

            //验证游戏终端
            /*
            $where['app_server_id'] = $appServerId;
            $where['app_platform_type_id'] = $appPlatformTypeId;
            $where['app_client_type_id'] = $appClientTypeId;
            if (Db::name('Game')->where($where)->count()) {
                $this->layJson(1, '已经存在该终端，请重新选择');
            }*/

            $gameId = Db::name('Game')->max('game_id') + 1;

            $add1 = Db::name('Game')->insert([
                'game_id' => $gameId,
                'game_name' => $gameName,
                'app_server_id' => $appServerId,
                'app_platform_type_id' => $appPlatformTypeId,
                'app_client_type_id' => $appClientTypeId,
                'up_location' => $upLocation,
                'online_time_region' => $onlineTimeRegion ? changeGameTime($onlineTimeRegion) : '0-0',
                'plat_show_region' => $platShowRegion ? changeGameTime($platShowRegion) : '0-0',
                'charge_time_region' => $chargeTimeRegion ? changeGameTime($chargeTimeRegion) : '0-0',
                'reg_time_region' => $regTimeRegion ? changeGameTime($regTimeRegion) : '0-0',
                'login_time_region' => $loginTimeRegion ? changeGameTime($loginTimeRegion) : '0-0',
                'pack_time_region' => $packTimeRegion ? changeGameTime($packTimeRegion) : '0-0',
                'h5_game_url' => $h5GameUrl,
                'pay_callback' => $payCallback,
                'rebate_callback' => $rebateCallback,
                'gm_callback' => $gmCallback,
                'secret' => $secret,
                'sdk_version' => $sdkVersion,
                'add_time' => time(),
                'status' => 1,
            ]);

            //游戏扩展表
            $add2 = Db::name('GameExtend')->insert([
                'game_id' => $gameId
            ]);

            //联运游戏配置表
            $secret = Db::name('ViewGameManage')->where('game_id', $gameId)->value('secret');

            $add3 = Db::name('ChannelGameConf')->insert([
                'game_id' => $gameId,
                'game_name' => $gameName,
                'channel_id' => 1000,
                'channel_name' => 'miyu',
                'code' => 'my',
                'version' => '1.0',
                'app_id' => $gameId,
                'app_secret' => $secret,
                'callback' => 'http://hw.sdkdrive.miyugame.com/paynotify/'.$gameId.'/miyu',
            ]);

            //删除模板缓存
            del_dir(RUNTIME_PATH . 'temp');

            $add1 ? $this->layJson(0, '添加成功') : $this->layJson(1, '添加失败，请重试');
        } else {
            $select = Db::name('AppServer')->field('id,app_type_id,app_publish_type_id,game_name')->where('status', '<>', -1)->order('id desc')->select();
            $appTypeIdName = changeValKey('AppType', 'id', 'name');
            $appPublishIdName = changeValKey('AppPublishType', 'id', 'name');

            $appServerId = [];
            foreach ($select as $k => $v) {
                $appServerId[] = [
                    'id' => $v['id'],
                    'app_type_name' => isset($appTypeIdName[$v['app_type_id']]) ? $appTypeIdName[$v['app_type_id']] : '',
                    'app_publish_type_name' => isset($appPublishIdName[$v['app_publish_type_id']]) ? $appPublishIdName[$v['app_publish_type_id']] : '',
                    'game_name' => $v['game_name'],
                ];
            }
            $appPlatformTypeId = Db::name('AppPlatformType')->select();
            $appClientTypeId = Db::name('AppClientType')->select();

            return view('', ['app_server_id' => $appServerId, 'app_platform_type_id' => $appPlatformTypeId, 'app_client_type_id' => $appClientTypeId]);
        }
    }

    //游戏终端编辑
    public function clientEdit()
    {
        if (request()->isAjax()) {
            $gameId = input('game_id');
            $gameName = input('game_name');
            $appServerId = input('app_server_id');
            $appPlatformTypeId = input('app_platform_type_id');
            $appClientTypeId = input('app_client_type_id');
            $upLocation = input('up_location');
            $sdkVersion = input('sdk_version');
            $h5GameUrl = input('h5_game_url');
            $payCallback = input('pay_callback');
            $rebateCallback = input('rebate_callback');
            $gmCallback = input('gm_callback');
            $secret = input('secret');
            $onlineTimeRegion = input('online_time_region');
            $platShowRegion = input('plat_show_region');
            $chargeTimeRegion = input('charge_time_region');
            $regTimeRegion = input('reg_time_region');
            $loginTimeRegion = input('login_time_region');
            $packTimeRegion = input('pack_time_region');
            $status = input('status');
            $appleRecharge = input('apple_recharge');
            $appleFloat = input('apple_float');

            if (isset($status)) {
                $update = Db::name('Game')->where('game_id', $gameId)->update(['status' => $status]);
                $update !== false ? $this->layJson(0, '修改成功') : $this->layJson(1, '修改失败，请重试');
            }

            //隐藏浮点
            if($appleFloat==0){
                if( !Db::name('FloatBall')->where(['game_id'=>input('game_id'), 'client_id'=>101, 'float_ball_display'=>0])->count() ){
                    Db::name('FloatBall')->insert(['game_id'=>$gameId, 'client_id'=>101, 'float_ball_display'=>0]);
                }
            }else{
                if( Db::name('FloatBall')->where(['game_id'=>input('game_id'), 'client_id'=>101, 'float_ball_display'=>0])->count() ){
                    Db::name('FloatBall')->where(['game_id'=>input('game_id'), 'client_id'=>101, 'float_ball_display'=>0])->delete();
                }
            }

            //验证游戏终端
            /*
            $where['app_server_id'] = $appServerId;
            $where['app_platform_type_id'] = $appPlatformTypeId;
            $where['app_client_type_id'] = $appClientTypeId;
            $where['game_id'] = ['<>', $gameId];
            if (Db::name('Game')->where($where)->count()) {
                $this->layJson(1, '已经存在该终端，请重新选择');
            }*/

            $update = Db::name('Game')->where('game_id', $gameId)->update([
                'game_name' => $gameName,
                'app_server_id' => $appServerId,
                'app_platform_type_id' => $appPlatformTypeId,
                'app_client_type_id' => $appClientTypeId,
                'up_location' => $upLocation,
                'online_time_region' => $onlineTimeRegion ? changeGameTime($onlineTimeRegion) : '0-0',
                'plat_show_region' => $platShowRegion ? changeGameTime($platShowRegion) : '0-0',
                'charge_time_region' => $chargeTimeRegion ? changeGameTime($chargeTimeRegion) : '0-0',
                'reg_time_region' => $regTimeRegion ? changeGameTime($regTimeRegion) : '0-0',
                'login_time_region' => $loginTimeRegion ? changeGameTime($loginTimeRegion) : '0-0',
                'pack_time_region' => $packTimeRegion ? changeGameTime($packTimeRegion) : '0-0',
                'h5_game_url' => $h5GameUrl,
                'pay_callback' => $payCallback,
                'rebate_callback' => $rebateCallback,
                'gm_callback' => $gmCallback,
                'secret' => $secret,
                'sdk_version' => $sdkVersion,
                'apple_recharge' => $appleRecharge,
            ]);

            //清楚缓存
            $enArr['gameId'] = $gameId;
            $args= json_encode($enArr);
            $clientId = 113;
            $class = 'Other';
            $method = 'updateGame';
            $secret = '8e50d1bac9bf3e49cb7cca55b2133ec2';
            $str = 'args='.$args.'&clientId='.$clientId.'&class='.$class.'&clientId='.$clientId.'&method='.$method.'&key='.$secret;
            $sign = md5($str);
            http('http://hw.dc.miyugame.com/Rpc', ['class' => 'Other', 'method'=>'updateGame', 'args'=>json_encode($enArr), 'clientId'=>113, 'sign'=>$sign]);

            $update !== false ? $this->layJson(0, '编辑成功') : $this->layJson(1, '编辑失败，请重试');
        } else {
            $find = Db::name('Game')->where('game_id', input('game_id'))->find();
            $find['online_time_region'] = explodeGameTime($find['online_time_region']);
            $find['plat_show_region'] = explodeGameTime($find['plat_show_region']);
            $find['charge_time_region'] = explodeGameTime($find['charge_time_region']);
            $find['reg_time_region'] = explodeGameTime($find['reg_time_region']);
            $find['login_time_region'] = explodeGameTime($find['login_time_region']);
            $find['pack_time_region'] = explodeGameTime($find['pack_time_region']);
            if($find['apple_recharge']==''){
                $find['apple_recharge'] = 0;
            }

            $appFloat = Db::name('FloatBall')->where(['game_id'=>input('game_id'), 'client_id'=>101, 'float_ball_display'=>0])->count();
            if($appFloat){
                $find['apple_float'] = 0;
            }else{
                $find['apple_float'] = 1;
            }

            $select = Db::name('AppServer')->field('id,app_type_id,app_publish_type_id,game_name')->where('status', '<>', -1)->order('id desc')->select();
            $appTypeIdName = changeValKey('AppType', 'id', 'name');
            $appPublishIdName = changeValKey('AppPublishType', 'id', 'name');

            $appServerId = [];
            foreach ($select as $k => $v) {
                $appServerId[] = [
                    'id' => $v['id'],
                    'app_type_name' => isset($appTypeIdName[$v['app_type_id']]) ? $appTypeIdName[$v['app_type_id']] : '',
                    'app_publish_type_name' => isset($appPublishIdName[$v['app_publish_type_id']]) ? $appPublishIdName[$v['app_publish_type_id']] : '',
                    'game_name' => $v['game_name'],
                ];
            }
            $appPlatformTypeId = Db::name('AppPlatformType')->select();
            $appClientTypeId = Db::name('AppClientType')->select();

            return view('', ['find' => $find, 'app_server_id' => $appServerId, 'app_platform_type_id' => $appPlatformTypeId, 'app_client_type_id' => $appClientTypeId]);
        }
    }

    //游戏版本删除
    public function clientDel()
    {
        $delRs = Db::name('Game')->where('game_id', input('game_id'))->update(['status' => -1]);
        $delRs !== false ? $this->layJson(0, '删除成功') : $this->layJson(1, '删除失败，请重试');
    }

    //上传
    public function upload()
    {

        if (request()->isAjax()) {
//            try {
                $file = request()->file('file');
                $gameId = input('server.http_game');

                empty($gameId) && $this->layJson(1, '请先选择游戏');

                $originPath = ROOT_PATH . '/uploads/apk/origin/';
                $unpackPath = ROOT_PATH . '/uploads/apk/unpack/' . $gameId;

                //上传文件，验证后缀跟文件大小，同名覆盖
                $info = $file
                    ->validate(['size' => 800000000, 'ext' => 'apk'])//800M
                    ->move($originPath, $gameId);
                if (!$info) {
                    $this->layJson(1, $file->getError());
                }

                //上传后的文件完整路径
                $filePath = $originPath . $info->getSaveName();

                //sh文件
                $cmd = "/data/apk/shell/unpack.sh";

                //未打包目录
                !is_dir($unpackPath) && mkdir($unpackPath);
                shell_exec("$cmd $filePath $unpackPath");//  > /dev/null 2>&1 &

                //删除apktool.yml中的压缩选项
                $apkFile = $unpackPath . "/apktool.yml";
                !is_file($apkFile) && $this->layJson(1, '不是一个有效的母包，请重新上传');

                $content = file_get_contents($apkFile);
                $pattern = '/doNotCompress:([\s\S]*)isFrameworkApk:/';
                $replacement = "doNotCompress:\nisFrameworkApk:";

                if (is_file($apkFile)) {
                    $content = preg_replace($pattern, $replacement, $content);
                    file_put_contents($apkFile, $content);
                } else {
                    $this->layJson(1, 'apktool.yml 不存在,文件解压失败');
                }

                $match = [];
                $packageName = '';
                $versionCode = '';
                $versionName = '';
                $apkSize = filesize($filePath);
                $apkSize === false && $apkSize = 0;

                $manifestFile = $unpackPath . "/AndroidManifest.xml";

                if (is_file($manifestFile)) {
                    $content = file_get_contents($manifestFile);
                    $pattern = '/<manifest.* package="(.*?)".*>/';
                    preg_match($pattern, $content, $match);
                    $packageName = $match['1'];

                    $pattern = '/<manifest.*VersionName="(.*)".*>/';
                    preg_match($pattern, $content, $match);
                } else {
                    $this->layJson(1, 'AndroidManifest.xml 不存在,文件解压失败');
                }

                $cmd = "/usr/bin/aapt dump badging {$filePath}";
                $apkInfo = @shell_exec($cmd);

                if ($apkInfo) {
                    $pattern = "/.*package: *name=['|\"](.*?)['|\"] ?.*/";
                    preg_match($pattern, $apkInfo, $match);
                    $packageName = $match['1'];

                    $pattern = "/.*versionCode=['|\"](.*?)['|\"] ?.*/";
                    preg_match($pattern, $apkInfo, $match);
                    $versionCode = $match['1'];

                    $pattern = "/.*versionName=['|\"](.*?)['|\"] ?.*/";
                    preg_match($pattern, $apkInfo, $match);
                    $versionName = $match['1'];

                    $pattern = "/.*platformBuildVersionName=['|\"](.*?)['|\"] ?.*/";
                    preg_match($pattern, $apkInfo, $match);
                } else {
                    $this->layJson(1, '获取apk信息失败');
                }

                //修改game
                $update['package_name'] = $packageName;
                $update['version_code'] = $versionCode;
                $update['version_str'] = $versionName;
                $update['source_path'] = "/uploads/apk/origin/{$gameId}.apk";
                $update['unpack_path'] = "/uploads/apk/unpack/{$gameId}";
                $update['package_size'] = $apkSize;

                $rs = Db::name('Game')->where('game_id', $gameId)->update($update);
                if ($rs > 0) {
                    $this->layJson(0, '上传安卓包成功', ['package_name' => $packageName, 'package_size' => round($apkSize / 1024 / 1024, 2) . 'MB', 'version_str' => $versionName]);
                } else {
                    @unlink($filePath);
                    $this->layJson(1, '上传包失败，请重试');
                }
//            }catch (\Exception $e){
//                $this->layJson(1, '上传异常:'.$e->getMessage());
//            }
        } else {
            $gameId = input('game_id'); //游戏id
            $find = Db::name('ViewGameManage')
                ->field('game_id,game_name,package_size,package_name,version_str')
                ->where('game_id', $gameId)
                ->find();
            $find['package_size'] = $find['package_size'] ? round($find['package_size'] / 1024 / 1024, 2) . 'MB' : '';
            return view('', ['find' => $find]);
        }

    }
}